package atguigu.demo2

import scala.io._
import scala.util.control.Breaks._

/**
  * Created by lzd on 2018/10/25.
  */
object demo2 {
  val x = 2

  def main(args: Array[String]): Unit = {
    /** if  else */

    // 类型不一样时，返回公共超类型Any
    val ifelse = if (x > 1) "hello" else 2
    // 如果没有值，则返回Unit，类似于Java 的Void
    if (x > 3) 1
    if (x > 0) 1 else ()

    var n = 10
    var w = 2
    // 如果多行表达式卸载一行需要分号，单个表达式可以不用大括号
    val nw = if (n > 0) {
      n = n * w;
      w += 1
    }
    println(nw) //无返回值
    println(n)
    println(w)

    val nw2 = if (n > 0) {
      n = n * w
      w += 1
    }
    println(nw2) //无返回值

    /** inout */
    print("Answer: ")
    println(42)

    println("Answer: " + 42)
    //%n 表示换行
    printf("Hello, %s! You are %d years old.%n", "Fred", 42)

    val name = "Fred"
    val age = 42.333333

    print(f"Hello, $name! You are $age%7.2f years old%n")

    val name2 = StdIn.readLine("Your name: ")

    print("Your age: ")
    val age2 = StdIn.readInt()

    println(f"Hello, $name2! Next year, you will be ${age2 + 1}.", name, age + 1)

    /** break */
    var rr = 1
    var nn = 10
    breakable(
      while (n > 0) {
        rr = rr * nn
        nn -= 1
        println(rr)
        if (rr == 720) break;
      }
    )

    /** 多变量 */
    for (i <- 1 to 3; j <- 4 to 7) {
      println(f"多变量计算结果 = ${i * j}")
    }

    //守卫模式
    for (i <- 1 to 3; j <- 1 to 3; if i == j) {
      println(f"守卫模式计算结果 = ${i * j}")
    }

    //多个守卫模式
    for (i <- 1 to 3; j <- 1 to 3; if i == j; if j != 2) {
      println(f"多个守卫模式计算结果 = ${i * j}")
    }

    // 引入变量
    for (i <- 1 to 3; blfrom = 4 - i; j <- blfrom to 3) {
      println(f"引用变量计算结果 = ${i * j}")
    }

    //使用变量
    for (i <- 1 to 3; from = 3 - i) {
      println(f"使用变量计算结果 ：i = $i ，from = $from")
    }

    //() 变成{}也可以
    for {i <- 1 to 3; from = 3 - i} {
      println(f"使用变量计算结果 ：i = $i ，from = $from")
    }

    //yield 将输出的结果放到集合,这种类型叫做for的推倒式
    val yieldres = for (i <- 1 to 3) yield i * 10
    println(yieldres)

    // for推导式返回的类型和第一个生成器的类型是兼容的
    println(for (c <- "Hello"; i <- 0 to 1) yield (c + i))
    println(for (i <- 0 to 1; c <- "Hello") yield (c + i))
  }
}



